import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class PlayHistoryItem {
  final String name;
  final String title;
  final String url;
  final String? siteName;
  final String? cover;
  final String? sourceSite; // 播放源站点名称
  final int time; // epoch seconds

  PlayHistoryItem({required this.name, required this.title, required this.url, this.siteName, this.cover, this.sourceSite, required this.time});

  Map<String, dynamic> toJson() => {
        'name': name,
        'title': title,
        'url': url,
        'siteName': siteName,
        'cover': cover,
        'sourceSite': sourceSite,
        'time': time,
      };

  static PlayHistoryItem fromJson(Map<String, dynamic> json) => PlayHistoryItem(
        title: json['title']?.toString() ?? '',
        name: json['name']?.toString() ?? '',
        url: json['url']?.toString() ?? '',
        siteName: json['siteName']?.toString(),
        cover: json['cover']?.toString(),
        sourceSite: json['sourceSite']?.toString(),
        time: (json['time'] is int) ? json['time'] as int : int.tryParse('${json['time'] ?? 0}') ?? 0,
      );
}

class HistoryStore {
  static const _key = 'play_history';

  static Future<List<PlayHistoryItem>> load() async {
    print('历史记录加载: 开始');
    final prefs = await SharedPreferences.getInstance();
    final raw = prefs.getString(_key);
    if (raw == null || raw.isEmpty) {
      print('历史记录加载: 无数据');
      return [];
    }
    try {
      final list = (jsonDecode(raw) as List<dynamic>)
          .map((e) => PlayHistoryItem.fromJson(e as Map<String, dynamic>))
          .toList();
      return list;
    } catch (e) {
      print('历史记录加载失败: $e');
      return [];
    }
  }

  static Future<void> save(List<PlayHistoryItem> list) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_key, jsonEncode(list.map((e) => e.toJson()).toList()));
  }

  static Future<void> add(PlayHistoryItem item) async {
    print('添加历史记录: 标题=${item.title}, 封面=${item.cover}, 播放源=${item.sourceSite}');
    final list = await load();
    // 先去重，再插入头部
    final filtered = list.where((e) => e.url != item.url).toList();
    filtered.insert(0, item);
    // 保留最多 100 条
    await save(filtered.take(100).toList());
    print('历史记录保存完成');
  }

  static Future<void> clear() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_key);
  }

  /// 删除指定 URL 的单条历史记录
  static Future<void> deleteByUrl(String url) async {
    final list = await load();
    final filtered = list.where((e) => e.url != url).toList();
    await save(filtered);
  }
}